﻿using Kernelx.Contexts.Repositories;
using Kernelx.Contexts.Repositories.Core;
using System.Collections.Generic;

 
#if NETSTANDARD2_0
using System.Threading;
using System.Threading.Tasks;
#endif
 
namespace Kernelx.Contexts.Defaults.RepositoriesWaylays
{
    internal class ModelibOfWorkWaylay: IModelibOfWork
    {
        private IModelibOfWork _modelibOfWork;
        private WaylaySettings _settings;

        public ModelibOfWorkWaylay(WaylaySettings  settings,IModelibOfWork modelibOfWork)
        {
            _modelibOfWork = modelibOfWork;
            _settings = settings;
        }

        public bool IsTransactioning => _modelibOfWork.IsTransactioning;

        public ITransaction BeginTransaction()=> _modelibOfWork.BeginTransaction();

        public void Dispose()
        {
            _modelibOfWork.Dispose();
            _modelibOfWork=null; 
            
            _stores?.Clear();
            _stores = null;

            _settings =null;
        }

        public int SaveChanges()=> _modelibOfWork.SaveChanges();


        private Dictionary<string, object> _stores = new Dictionary<string, object>();
        public IModelStore<T> Store<T>(string targetName = null) where T : class, new()
        {
            IModelStore<T> result = null;
            var key = targetName ?? typeof(T).Name; 
            if (!_stores.ContainsKey(key))
            {
                lock (_stores)
                    if (!_stores.ContainsKey(key))
                        _stores.Add(key, result = new ModelStoreMaylay<T>(_modelibOfWork.Store<T>(targetName)));
            }
            return result ?? _stores[key] as IModelStore<T>;
        } 




#if NETSTANDARD2_0
        public async Task<int> SaveChangesAsync(CancellationToken token = default)
        =>await _modelibOfWork.SaveChangesAsync(token);
#endif

    }
}
